package com.qding.park.manager.service.core.facade.impl.common;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qding.park.common.core.cache.service.CacheServiceFacade;
import com.qding.park.common.core.exceptions.BaseException;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.manager.service.ServiceCoreException;
import com.qding.park.common.core.exceptions.business.payment.PaymentException;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.facade.core.service.common.PayCommonFacade;
import com.qding.park.manager.facade.core.service.enums.TempPaymentEnum;
import com.qding.park.manager.payment.PaymentInterfaceServiec;
import com.qding.park.manager.pojo.TbMonthRent;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.TbReserve;
import com.qding.park.manager.pojo.enums.MonthRentStatuEnum;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.enums.ReserverTypeEnum;
import com.qding.park.manager.pojo.payment.AbstractResult;
import com.qding.park.manager.pojo.payment.OrderParameter;
import com.qding.park.manager.pojo.payment.ResultCreateorder;
import com.qding.park.manager.service.core.biz.PayFeeBiz;
import com.qding.park.manager.service.core.mapper.TbMonthRentMapper;

@Service("payCommonFacade")
public class PayCommonFacadeImpl implements PayCommonFacade {

    private static final Logger _log = LoggerFactory.getLogger(PayCommonFacadeImpl.class);
    @Autowired
    private PayFeeBiz payFeeBiz;

    @Autowired
    private CacheServiceFacade cacheServiceFacade;

    /**
     * @Fields paymentInterfaceServiec : TODO（支付服务接口）
     */
    @Autowired
    private PaymentInterfaceServiec paymentInterfaceServiec;

    @Autowired
    private ParkCacheInter parkCacheInter;

    @Autowired
    private TbMonthRentMapper tbMonthRentMapper;

    @Override
    public ParkDataResult createmonthPayment(int parkId, String carNum, String bjuserId)
            throws BaseException {
        TbMonthRent tbMonthRent = new TbMonthRent();
        tbMonthRent.setParkID(parkId);
        tbMonthRent.setBjuserid(bjuserId);
        tbMonthRent.setCarNum(carNum);

        payFeeBiz.createMonthRentPay(tbMonthRent);

        ParkDataResult parkDataResult = ParkDataResult.createObjDate();
        parkDataResult.putDataOnObj("orderId", tbMonthRent.getId());
        parkDataResult.putDataOnObj("parkId", tbMonthRent.getParkID());
        parkDataResult.putDataOnObj("parkName", tbMonthRent.getParkName());
        parkDataResult.putDataOnObj("cardExpiration",
                tbMonthRent.getOldExpiredate() == null ? 0 : tbMonthRent.getOldExpiredate().getTime() / 1000);

        return parkDataResult;
    }

    @Override
    public ParkDataResult createTempPayment(int parkId, String carNum, String bjuserId, TempPaymentEnum tempPaymentEnum)
            throws BaseException {
        // 临停缴费
        TbReserve reserver = new TbReserve();
        reserver.setParkID(parkId);
        reserver.setCarNum(carNum);
        reserver.setBjuserId(bjuserId);
        if (tempPaymentEnum == TempPaymentEnum.TEMP) {
            reserver.setReserverType(ReserverTypeEnum.UNRESERVER.getType());
            payFeeBiz.createTempPayment(reserver);
        } else if (tempPaymentEnum == TempPaymentEnum.TENERAT) {
            reserver.setReserverType(ReserverTypeEnum.GENERATION.getType());
            payFeeBiz.createTeneratPayment(reserver);
        }
//        reserver.setReserverType(ReserverTypeEnum.UNRESERVER.getType());
        
        
        // 创建临停缴费单

        ParkDataResult parkDataResult = ParkDataResult.createObjDate();
        parkDataResult.putDataOnObj("orderId", reserver.getId());
        parkDataResult.putDataOnObj("parkId", reserver.getParkID());
        parkDataResult.putDataOnObj("parkName", reserver.getParkName());
        parkDataResult.putDataOnObj("startTime", reserver.getCheckInTime().getTime() / 1000);
        parkDataResult.putDataOnObj("endTime", reserver.getCheckOutTime().getTime() / 1000);
        parkDataResult.putDataOnObj("parkFee", reserver.getDeposit());
//        parkDataResult.putDataOnObj("parkFee", reserver.getDeposit());
        if (reserver.getStartTime() != null) {
            parkDataResult.putDataOnObj("reserveTime", reserver.getStartTime().getTime() / 1000);
        }

        /***** 缓存订单信息 **********/
        /***** 缓存订单信息 **********/
        _log.info("创建　了临停缴费单:" + reserver.getId());

        return parkDataResult;
    }

    @Override
    public ParkDataResult calMonthFee(String orderId, int monthNum) throws BaseException {
        ParkDataResult parkDataResult = new ParkDataResult();

        TbMonthRent tbMonthRent = new TbMonthRent();
        tbMonthRent.setId(orderId);
        tbMonthRent.setBuyMonths(monthNum);
        TbMonthRent tbmon = payFeeBiz.calMonthFee(tbMonthRent);
        /******************/

        parkDataResult.putDataOnObj("totalFee", tbmon.getCost());
        if (tbmon.getExpiredate() != null) {
            parkDataResult.putDataOnObj("expirationTime", tbmon.getExpiredate().getTime() / 1000);
        }

        return parkDataResult;
    }

    @Override
    public ParkDataResult createTemPayOrder(String orderId) throws BaseException {
        TbReserve reserve = payFeeBiz.createTemPayOrder(orderId);
        ParkDataResult dataResult = ParkDataResult.createObjDate();
        dataResult.putDataOnObj("szOrderId", reserve.getId());
        dataResult.putDataOnObj("bjOrderId", reserve.getBjOrderId());
        return dataResult;
    }

    @Override
    public ParkDataResult createTeneratPayOrder(String orderId) throws BaseException {
        TbReserve reserve = payFeeBiz.createTemPayOrder(orderId);
        ParkDataResult dataResult = ParkDataResult.createObjDate();
        dataResult.putDataOnObj("szOrderId", reserve.getId());
        dataResult.putDataOnObj("bjOrderId", reserve.getBjOrderId());
        return dataResult;
    }

    @Override
    public ParkDataResult createMonthPayOrder(String orderId) throws BaseException {
        TbMonthRent tbMonthRent = cacheServiceFacade.monthrentPay_cache_query(orderId);
        int parkId = tbMonthRent.getParkID();
        if (tbMonthRent == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(), "订单已失效",
                            " orderId=" + orderId));
        }

        // 订单
        // TbMonthRent tbMonthRent = SerializeUtils.unSerialize(orderStr,
        // TbMonthRent.class);

        if (StringUtils.isBlank(tbMonthRent.getBjOrderId())) {
            TbParkspace tbParkspace = parkCacheInter.queryParkSpace(parkId);
            int orderType = OrderParameter.OrderTypeEnum.MONTH_PAY_TYPE.getType();
            int totalPrice = tbMonthRent.getCost();
            int orderSource = OrderSourceEnum.APP.getType();
            String szCarpassId = tbMonthRent.getId();
            String memberId = tbMonthRent.getBjuserid();
            OrderParameter orderparameter = new OrderParameter();
            orderparameter.setOrderType(orderType);
            orderparameter.setTotalPrice(totalPrice);
            orderparameter.setOrderSource(orderSource);
            orderparameter.setSzCarpassId(szCarpassId);
            orderparameter.setMemberId(memberId);
            orderparameter.setProjectId(tbParkspace.getBjprojectId());

            ResultCreateorder resultCreateorder = paymentInterfaceServiec.createOrder(orderparameter);
            if (resultCreateorder.getCode() != AbstractResult.ResultCodeEnum.SUCESS.getCode()) {
                throw new PaymentException(PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getId(), null,
                        ExceptionMessage.createExceptionMessage(
                                PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getDesc(),
                                "创建订单失败pay-platform:" + resultCreateorder.getMessage(),
                                " orderType=" + orderType + ",totalPrice=" + totalPrice + ",orderSource" + orderSource
                                        + ",szCarpassId=" + szCarpassId + ",memberId=" + memberId + ",orderId"
                                        + orderId));
            }

            String bjOrderId = resultCreateorder.getOrderId();
            tbMonthRent.setBjOrderId(bjOrderId);
            tbMonthRent.setCreate_date(new Date());
            tbMonthRent.setStatus(MonthRentStatuEnum.NOT_PAY.getStatus());
            tbMonthRent.setUpdate_date(new Date());
            tbMonthRent.setOrderSource(orderSource);
            // int num = tbReserveMapper.save(reserve);
            int num = tbMonthRentMapper.save(tbMonthRent);
            cacheServiceFacade.monthrentPay_cache_add(tbMonthRent);
        }

        ParkDataResult dataResult = ParkDataResult.createObjDate();
        dataResult.putDataOnObj("szOrderId", orderId);
        dataResult.putDataOnObj("bjOrderId", tbMonthRent.getBjOrderId());
        return dataResult;
    }

    @Override
    public ParkDataResult monthPaySuccessNotice(String orderId, int realPayAmount) throws BaseException {
        payFeeBiz.monthPaySuccessNotice(orderId, realPayAmount);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult teneratPaySuccessNotice(String orderId, int realPayAmount) throws BaseException {
        payFeeBiz.teneratPaySuccessNotice(orderId, realPayAmount);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult reserverPaySuccessNotice(String orderId, int realPayAmount) throws BaseException {
        payFeeBiz.reserverPaySuccessNotice(orderId, realPayAmount);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult tempPaySuccessNotice(String orderId, int realPayAmount) throws BaseException {
        payFeeBiz.tempPaySuccessNotice(orderId, realPayAmount);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult monthPayFailNotice(String orderId) throws BaseException {
        payFeeBiz.monthPayFailNotice(orderId);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult teneratPayFailNotice(String orderId) throws BaseException {
        payFeeBiz.tempPayFailNotice(orderId);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult reserverPayFailNotice(String orderId) throws BaseException {
        payFeeBiz.reserverPayFailNotice(orderId);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult tempPayFailNotice(String orderId) throws BaseException {
        payFeeBiz.tempPayFailNotice(orderId);
        return ParkDataResult.createEmpty();
    }

}
